package com.cn.longdistancebusstation.busInfo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.registerAndLogin.LoginActivity;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.adapter.StationPointAdapter;
import com.cn.longdistancebusstation.annotation.LoginStatus;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.WebService;
import com.cn.longdistancebusstation.model.BusInfo;
import com.cn.longdistancebusstation.model.Station;
import com.cn.longdistancebusstation.order.ConfirmOrderActivity;
import com.cn.longdistancebusstation.util.DateUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BusInfoListActivity extends BaseActivity implements OnRecyclerViewItemClickListener,View.OnClickListener
{

    private Button mPreBtn;
    private Button mNextBtn;
    private TextView mDateTextView;
    private RecyclerView mRecyclerView;
    private List<BusInfo> mBusInfoList=new ArrayList<>();
    private List<Contacter> mContacterlist;
    private List<Station> mPassStationList;
    private CustomAdapter mAdapter;
    private Set<BusInfo> receivers;
    private Set<BusInfo> value = new HashSet<BusInfo>();
    //目的地站点
    private Station mDesStation;
    //出行时间
    private String mOutingDate;
    BusInfo busInfo = null;
    private LinearLayout parentLayout;
    private RelativeLayout childLayout;
    private LinearLayout mLinearLayout;

    private StationPointAdapter spAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bus_list);
        this.getTitleTextView().setText("车次列表");
        initData();
//        registerBroadcast();
    }

    private void initData(){
        parentLayout=(LinearLayout)findViewById(R.id.parent_layout);
        childLayout=(RelativeLayout)findViewById(R.id.child_layout);
        mLinearLayout=(LinearLayout)findViewById(R.id.main_layout);
        mPreBtn = (Button)findViewById(R.id.btn_pre);
        mNextBtn = (Button)findViewById(R.id.btn_next);
        mDateTextView = (TextView)findViewById(R.id.textView_date);
        mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter = new CustomAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setmOnRecyclerViewItemClickListener(this);

        //
        mBusInfoList = new ArrayList<>();
        mPassStationList = new ArrayList<>();
        //
        Intent intent = getIntent();
        mOutingDate = intent.getStringExtra("date");
        mDesStation = (Station) intent.getSerializableExtra("station");
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        mDateTextView.setText(dateFormat.format(date));
        mDateTextView.setText(mOutingDate);

        getBusInfoList();
    }

    /*
* 获取车次列表
* */
    private void getBusInfoList(){
        mBusInfoList.clear();
        Retrofit retrofit = new HttpHelper.WebServiceBuilder().build().getRetrofit();
        WebService webService = retrofit.create(WebService.class);
        Date today = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strToday = dateFormat.format(today);
        Call<String> call = webService.getNewBusList(mDesStation.getStationID(), mOutingDate, dateFormat.format(today));
        showHud();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                hideHud();
                try
                {
                    parseXMLForBusList(response.body());
                    mAdapter.notifyDataSetChanged();
                }
                catch(XmlPullParserException e)
                {}
                catch(IOException e)
                {}
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                hideHud();
                Toast.makeText(BusInfoListActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void parseXMLForBusList(String xmlText) throws XmlPullParserException, IOException{
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlPullParser = factory.newPullParser();
        xmlPullParser.setInput(new StringReader(xmlText));
        int eventType = xmlPullParser.getEventType();
        Log.d("车次列表数据",xmlText);
        String strTagName = "";
        String strTagText = "";
        Boolean isShow = false;
        while(eventType != XmlPullParser.END_DOCUMENT)
        {
            if(eventType == XmlPullParser.START_DOCUMENT)
            {}
            else if(eventType == XmlPullParser.START_TAG)
            {
                strTagName = xmlPullParser.getName();
                if(strTagName.equals("MobilportBliidListAPP"))
                {
                    busInfo = new BusInfo();
                    busInfo.setToStation(mDesStation);
                }
            }
            else if(eventType == XmlPullParser.END_TAG)
            {
                strTagName = "";
                if(xmlPullParser.getName().equals("MobilportBliidListAPP") && isShow)
                {
                    if(busInfo.getLeftTickets()-busInfo.getSoldTickets() > 0)
                    {
                        mBusInfoList.add(busInfo);
                    }
                }
            }
            else if(eventType == XmlPullParser.TEXT)
            {
                strTagText = xmlPullParser.getText();
                if(strTagName.equals("IsFromGate"))
                {
                    busInfo.setSupportPickUpService(strTagText.equals("可上门接"));
                }
                else if(strTagName.equals("FromStatement"))
                {
                    busInfo.setPickUpServiceDesc(strTagText);
                }
                else if(strTagName.equals("IsToGate"))
                {
                    busInfo.setSupportSendService(strTagText.equals("可送站"));
                }
                else if(strTagName.equals("ToStatement"))
                {
                    busInfo.setSendServiceDesc(strTagText);
                }
                else if(strTagName.equals("ToGateFee"))
                {
                    busInfo.setSendServiceFee(strTagText);
                }
                else if(strTagName.equals("FromGateFee"))
                {
                    busInfo.setPickUpServiceFee(strTagText);
                }
                else if(strTagName.equals("SendStationName"))
                {
                    busInfo.setStartStationName(strTagText);
                }
                else if(strTagName.equals("PortName"))
                {
                    busInfo.setEndStationName(strTagText);
                }
                else if(strTagName.equals("BusKindName"))
                {
                    busInfo.setBusType(strTagText);
                }
                else if(strTagName.equals("BliidIsCanSellTicket"))
                {
                    if(strTagText.equals("不可售")) isShow = false;
                    else isShow = true;
                }
                else if(strTagName.equals("Bliid"))
                {
                    busInfo.setBusNo(strTagText);
                }
                else if(strTagName.equals("BliidSendTime"))
                {
                    busInfo.setSendTime(strTagText);
                }
                else if(strTagName.equals("BliidCheckWindowID"))
                {
                    busInfo.setCheckWindowID(strTagText);
                }
                else if(strTagName.equals("PortPrice"))
                {
                    busInfo.setTicketPrice(strTagText);
                }
                else if(strTagName.equals("BliidCanSellNum"))
                {
                    busInfo.setLeftTickets(Integer.parseInt(strTagText));
                }
                else if(strTagName.equals("BliidSelledNum"))
                {
                    busInfo.setSoldTickets(Integer.parseInt(strTagText));
                }
                else if(strTagName.equals("BliidIsFlow"))
                {
                    busInfo.setFlow(strTagText.equals("0")?false:true);
                }
                else if(strTagName.equals("BliidStartNum"))
                {
                    busInfo.setStartSeatNo(strTagText);
                }
            }
            eventType = xmlPullParser.next();
        }
        if(mBusInfoList.size()==0){
            parentLayout.setVisibility(View.GONE);
            childLayout.setVisibility(View.VISIBLE);
        }else{
            parentLayout.setVisibility(View.VISIBLE);
            childLayout.setVisibility(View.GONE);
        }

    }

    //获取中途经过站点
    private void getPassStations(String strBusNo){
        mPassStationList.clear();
        showHud();
        Retrofit retrofit = new HttpHelper.WebServiceBuilder().build().getRetrofit();
        WebService webService = retrofit.create(WebService.class);
        Call<String> call = webService.getPassStations(strBusNo, mOutingDate);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                hideHud();
                try
                {
                    parseXMLForPassStations(response.body());
                    getStationPoint();
                }
                catch(XmlPullParserException e)
                {}
                catch(IOException e)
                {}
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                hideHud();
                Toast.makeText(BusInfoListActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void parseXMLForPassStations(String xmlText) throws XmlPullParserException, IOException{
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlPullParser = factory.newPullParser();
        xmlPullParser.setInput(new StringReader(xmlText));
        int eventType = xmlPullParser.getEventType();
        Log.d("途径站点列表数据",xmlText);
        String strTagName = "";
        String strTagText = "";
        Station station = null;
        while(eventType != XmlPullParser.END_DOCUMENT)
        {
            if(eventType == XmlPullParser.START_DOCUMENT)
            {}
            else if(eventType == XmlPullParser.START_TAG)
            {
                strTagName = xmlPullParser.getName();
                if(strTagName.equals("bliidPortDistance"))
                {
                    station = new Station();
                }
            }
            else if(eventType == XmlPullParser.END_TAG)
            {
                strTagName = "";
                if(xmlPullParser.getName().equals("bliidPortDistance"))
                {
                    mPassStationList.add(station);
                }
            }
            else if(eventType == XmlPullParser.TEXT)
            {
                strTagText = xmlPullParser.getText();
                if(strTagName.equals("SerialNo"))
                {
                    station.setStationID(strTagText);
                }
                else if(strTagName.equals("PortName"))
                {
                    station.setStationName(strTagText);
                }
            }
            eventType = xmlPullParser.next();
        }
    }

    public void onPreBtnClick(View view){
        Date today = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String strToday = dateFormat.format(today);
        if(mOutingDate.equals(strToday)){
            Toast.makeText(BusInfoListActivity.this, "已经是今天了", Toast.LENGTH_SHORT).show();
            return;
        }
        mOutingDate = DateUtil.getSpecifiedDayBefore(mOutingDate);
        mDateTextView.setText(mOutingDate);
        getBusInfoList();
    }

    public void onNextBtnClick(View view){
        mOutingDate = DateUtil.getSpecifiedDayAfter(mOutingDate);
        mDateTextView.setText(mOutingDate);
        getBusInfoList();
    }

    @Override
    public void onClick(int position) {

        //判断是否已登录，未登录则显示登录界面
        if(GlobalVariable.getLoginStatus() == LoginStatus.STATUS_LOGOUT){
            Intent intent = new Intent(BusInfoListActivity.this, LoginActivity.class);
            startActivity(intent);
        }
        else{
            BusInfo busInfo = mBusInfoList.get(position);
            if(busInfo.getLeftTickets()-busInfo.getSoldTickets() > 0){
                Intent intent = new Intent(this, ConfirmOrderActivity.class);
                intent.putExtra("busInfo", busInfo);
                intent.putExtra("outtingDate",mOutingDate);
                startActivity(intent);
            }
            else{
                Toast.makeText(BusInfoListActivity.this, "该车次没有票了", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onClickInnerCtrl(int position) {
        BusInfo busInfo = mBusInfoList.get(position);
        getPassStations(busInfo.getBusNo());
    }

    @Override
    public void onClickCoupon(int position) {

    }

    @Override
    public void onClickCheckBox(int position) {

    }

    private void getStationPoint() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_station_point, null);
        final TextView tv_adult = (TextView) view.findViewById(R.id.tv_adult);
        final ListView list_station_point=(ListView)view.findViewById(R.id.list_station_point);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_add_new_passengers, null);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });
        list_station_point.setAdapter(spAdapter);
        spAdapter=new StationPointAdapter(BusInfoListActivity.this,mPassStationList);
        list_station_point.setAdapter(spAdapter);



        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {

    }


    private class ItemViewHolder extends RecyclerView.ViewHolder{
        private TextView mSendDateTextView;
        private TextView mBusTypeTextView;
        private TextView mStartStationTextView;
        private TextView mEndStationTextView;
        private TextView mBusNoTextView;
        private TextView mPriceTextView;
        private TextView mDescTextView;
        private ImageView iv_down;
        private ImageView mSendOrPickUpToBustationImageView;
        public ItemViewHolder(View itemView){
            super(itemView);
            mSendDateTextView = (TextView)itemView.findViewById(R.id.textView_sendDate);
            mBusTypeTextView = (TextView)itemView.findViewById(R.id.textView_busType);
            mStartStationTextView = (TextView)itemView.findViewById(R.id.textView_fromStation);
            mEndStationTextView = (TextView)itemView.findViewById(R.id.textView_toStation);
            mBusNoTextView = (TextView)itemView.findViewById(R.id.textView_busNo);
            mPriceTextView = (TextView)itemView.findViewById(R.id.textView_price);
            mDescTextView = (TextView)itemView.findViewById(R.id.textView_desc);
            iv_down=(ImageView)itemView.findViewById(R.id.station_point);
            mSendOrPickUpToBustationImageView=(ImageView)itemView.findViewById(R.id.imageView_sendOrPickUpToStation);
        }

        public void bindData(BusInfo busInfo){
            String strSendTime = busInfo.getSendTime();
            if(busInfo.getFlow()){
                //流水车
                mSendDateTextView.setText("流水车");
            }
            else{
                mSendDateTextView.setText(strSendTime.split(" ")[1]);
            }
            mBusTypeTextView.setText(busInfo.getBusType());
            mStartStationTextView.setText(busInfo.getStartStationName());
            mEndStationTextView.setText(busInfo.getEndStationName());
            mBusNoTextView.setText("车次" + busInfo.getBusNo());
            BigDecimal decimal = new BigDecimal(busInfo.getTicketPrice());
            mPriceTextView.setText("￥"+decimal.toString());
            if(busInfo.getLeftTickets()-busInfo.getSoldTickets() > 0){
                mDescTextView.setText("有票");
            }
            else{
                mDescTextView.setText("无票");
            }
            //接送站服务的判断
            if(busInfo.getSupportPickUpService() && busInfo.getSupportSendService())
            {
                //接送站服务都支持
                mSendOrPickUpToBustationImageView.setVisibility(View.VISIBLE);
                mSendOrPickUpToBustationImageView.setBackground(getResources().getDrawable(R.mipmap.sendandpickuptobustation));
            }
            else if(busInfo.getSupportSendService())
            {
                //只支持送站
                mSendOrPickUpToBustationImageView.setVisibility(View.VISIBLE);
                mSendOrPickUpToBustationImageView.setBackground(getResources().getDrawable(R.mipmap.pickuptobustation));
            }
            else if(busInfo.getSupportPickUpService())
            {
                //只支持接站
                mSendOrPickUpToBustationImageView.setVisibility(View.VISIBLE);
                mSendOrPickUpToBustationImageView.setBackground(getResources().getDrawable(R.mipmap.sendtobustation));
            }
            else
            {
                //不支持接送站
                mSendOrPickUpToBustationImageView.setVisibility(View.GONE);
            }
        }
    }

    public class CustomAdapter extends RecyclerView.Adapter<ItemViewHolder>{

        private OnRecyclerViewItemClickListener mOnRecyclerViewItemClickListener;

        public void setmOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener mOnRecyclerViewItemClickListener) {
            this.mOnRecyclerViewItemClickListener = mOnRecyclerViewItemClickListener;
        }

        @Override
        public ItemViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
            View view = layoutInflater.inflate(R.layout.bus_info_list_item2, parent, false);
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ItemViewHolder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnRecyclerViewItemClickListener.onClick(position);
                }
            });
            BusInfo busInfo = mBusInfoList.get(position);
            holder.bindData(busInfo);
            holder.iv_down.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnRecyclerViewItemClickListener.onClickInnerCtrl(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mBusInfoList.size();
        }
    }


}
